<template>
  <el-row :gutter="4">
    <el-col :span="4">
      <el-menu default-active="0" class="el-menu-vertical-demo" @select="handleMenuClick">
        <el-menu-item index="0">
          <el-icon>
            <HomeFilled />
          </el-icon>
          <span>全部</span>
        </el-menu-item>
        <el-menu-item index="1">
          <el-icon class="mr-5px" icon="ep:dataLine">
            <ElementPlus />
          </el-icon>
          <span>图片</span>
        </el-menu-item>
        <el-menu-item index="2">
          <el-icon>
            <VideoCamera />
          </el-icon>
          <span>视频</span>
        </el-menu-item>
        <el-menu-item index="3">
          <el-icon>
            <Microphone />
          </el-icon>
          <span>音频</span>
        </el-menu-item>
        <el-menu-item index="4">
          <Icon class="mr-5px" icon="ep:document" />
          <span>Office文件</span>
        </el-menu-item>
        <el-menu-item index="5">
          <Icon class="mr-5px" icon="ep:document" />
          <span>在线文档</span>
        </el-menu-item>
        <el-menu-item index="6">
          <el-icon>
            <Paperclip />
          </el-icon>
          <span>压缩文件</span>
        </el-menu-item>
        <!-- <el-menu-item index="999">
          <el-icon>
             <Notification />
          </el-icon>
          <span>我的分享</span>
        </el-menu-item> -->
      </el-menu>
      <el-card>
        <el-link @click="handleMyShareClick"><el-icon>
            <Notification />
          </el-icon>
          <span class="ml-3">我的分享</span></el-link>
      </el-card>

    </el-col>
    <el-col :span="20" :xs="24">
      <ContentWrap class="!m-b-2">
        <!-- 搜索工作栏 -->
        <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="68px">
          <el-form-item>
            <el-button type="success" class="!m-l-1 !border-rd-0" @click="openUploadForm">
              <Icon icon="ep:upload" class="mr-5px" /> 上传文件
            </el-button>
            <el-button type="primary" class="!m-l-1 !border-rd-0" @click="openUpdateForm(undefined, 'online')">
              <Icon class="mr-5px" icon="ep:plus" />
              新建文档
            </el-button>
            <el-button type="warning" class="!m-l-1 !border-rd-0" @click="openFileNameForm(undefined)">
              <Icon class="mr-5px" icon="ep:plus" />
              新建目录
            </el-button>
          </el-form-item>
          <el-form-item prop="title">
            <el-input v-model="queryParams.title" clearable class="!w-360px" placeholder="输入关键字, 如：文件名称/目录名称">
              <template #append>
                <el-button type="primary" @click="handleQuery">
                  <Icon class="mr-5px" icon="ep:search" /> 搜索
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ElCard class="m-t-0">
        <template #header>
          <div class="flex items-center justify-between">
            <div class="flex items-center align-center">
              <Icon class="mr-5px" :size="22" icon="flat-color-icons:folder" />
              <el-breadcrumb separator="/">
                <el-breadcrumb-item v-for="item in breadcuembDataList" :key="item.id">
                  <el-link type="primary" class=" !cursor-pointer" @click="handleBreadcrumbClick(item)">{{ item.name
                  }}</el-link>
                </el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <div class="flex items-center align-center">
              <!-- <el-tooltip effect="light" content="选中所有文件">
                <el-checkbox class="!border-rd-0 !m-r-2" label="全选" border />
              </el-tooltip> -->
              <el-button-group>
                <el-button @click="handleBatchDelete"> 删除 </el-button>
                <el-button @click="handleBatchEdit"> 编辑 </el-button>
                <el-button @click="handleBatchShare(1)"> 共享文件 </el-button>
                <el-button @click="handleBatchShare(0)"> 取消共享 </el-button>
              </el-button-group>
            </div>
          </div>
        </template>
        <div v-if="list && list.length" v-loading="loading">
          <div class="flex flex-wrap justify-start items-center" v-show="list && list.length">
            <div v-for="item in list" :key="item.id" @dblclick="handleDoubleClick(item)"
              class="m-1.6 checkbox-wrapper-16">
              <label class="checkbox-wrapper">
                <input v-model="checkedFiles" class="checkbox-input" type="checkbox"
                  :disabled="folderDisabled && item.isFolder == 1" :key="String(item.id)" :value="String(item.id)" />
                <div class="w-36 h-42  checkbox-tile">
                  <div class="flex justify-end w-full h-7 m-t-4px m-r-6px z-999">
                    <el-dropdown placement="bottom-start">
                      <el-button size="small" type="primary" plain class="checkbox-dropdown"> 操作 </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="handleDownload(item)"
                            v-if="item.isFolder == 0 && item.fileClass != 5">下载</el-dropdown-item>

                          <el-dropdown-item v-if="item.creator == userStore.user.id"
                            @click="openUpdateForm(item.id, '')">编辑</el-dropdown-item>
                          <el-dropdown-item v-if="item.creator == userStore.user.id"
                            @click="handleDelete(item)">删除</el-dropdown-item>
                          <template v-if="item.isFolder == 0">
                            <el-dropdown-item @click="openViewForm(item)">查看</el-dropdown-item>
                            <el-dropdown-item v-if="item.isShare == 0 && item.creator == userStore.user.id"
                              @click="handleShare(item, 1)">共享</el-dropdown-item>
                            <el-dropdown-item v-if="item.isShare == 1 && item.creator == userStore.user.id"
                              @click="handleShare(item, 0)">取消共享</el-dropdown-item>
                          </template>

                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                  <div class="flex flex-col  m-t-1 justify-start items-center h-41">
                    <el-badge class="!w-20" :value="item.creator == userStore.user.id ? '我共享' : '他共享'"
                      :offset="[-20, 5]" :hidden="item.isShare == 0">
                      <!-- 根据不同文件类型,展示对应的图标 -->
                      <!-- 文件夹类型 -->
                      <template v-if="item.isFolder == 1">
                        <Icon :size="80" icon="flat-color-icons:folder" />
                      </template>
                      <template v-else>
                        <el-image v-if="item.fileClass == OaFileClassType.IMAGE" class="w-20 h-20 m-b-2"
                          :src="item.url" />
                        <Icon v-else-if="item.fileClass == OaFileClassType.AUDIO" :size="80"
                          icon="flat-color-icons:audio-file" />
                        <Icon v-else-if="item.fileClass == OaFileClassType.VIDEO" :size="80"
                          icon="flat-color-icons:video-file" />
                        <Icon v-else-if="item.fileClass == OaFileClassType.OFFICE" :size="80"
                          icon="vscode-icons:file-type-word2" />
                        <!-- todo 根据office不同文件后缀,展示对应的文件图标 -->
                        <Icon v-else-if="item.fileClass == OaFileClassType.RAR" :size="80" icon="openmoji:winrar" />
                        <Icon v-else-if="item.fileClass == OaFileClassType.ON_LINE" :size="80"
                          icon="flat-color-icons:document" />
                        <Icon v-else :size="80" icon="tdesign:file-unknown" />
                      </template>
                    </el-badge>
                    <el-tooltip effect="dark" :content="item.title" placement="bottom">
                      <el-text line-clamp="2" size="small" class="w-120px mx-1" align="center">{{ item.title
                      }}</el-text>

                    </el-tooltip>
                  </div>
                </div>
              </label>
            </div>
          </div>
        </div>
        <el-empty style="width: 100%;" v-else description="暂无数据" />
      </ElCard>
      <!-- 分页 -->
      <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
    </el-col>
  </el-row>

  <!-- 表单弹窗：添加/修改 -->
  <FileForm ref="openUploadFormRef" @success="getList" />
  <!-- 表单弹窗：添加/修改 -->
  <CreateFolderForm ref="formFileNameRef" @success="getList" />
  <!-- 修改文件或文件夹信息-->
  <UpdateFileForm ref="formUpdateRef" @success="getList" />
  <Dialog :title="officeView.title || '文档预览'" v-model="officeView.dialog" width="100vh" :fullscreen="true" top="5vh"
    :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" destroy-on-close>
    <vue-office-docx v-if="officeView.type == 'doc'" :src="officeView.url" style="height: 80vh;" />
    <vue-office-excel v-if="officeView.type == 'excel'" :options="officeView.xlsOptions" :src="officeView.url"
      style="height: 80vh;" />
    <vue-office-pdf v-if="officeView.type == 'pdf'" :src="officeView.url" style="height: 80vh;" />
    <AudioPlayer v-if="officeView.type == 'audio'" :src='officeView.url' />
  </Dialog>
</template>
<script lang="ts" setup>
import { HomeFilled, Microphone, VideoCamera, Paperclip, ElementPlus, Notification } from '@element-plus/icons-vue'
import { createImageViewer } from '@/components/ImageViewer'
import { createVideoViewer } from '@/components/VideoPlayer/index'
//引入VueOfficeDocx组件
import VueOfficeDocx from '@vue-office/docx'
//引入相关样式
import '@vue-office/docx/lib/index.css'
//引入VueOfficeExcel组件
import VueOfficeExcel from '@vue-office/excel'
//引入相关样式
import '@vue-office/excel/lib/index.css'
//引入VueOfficePdf组件
import VueOfficePdf from '@vue-office/pdf'

import * as FileApi from '@/api/infra/file'
import { OaFileClassType } from '@/utils/constants'
import FileForm from './FileForm.vue'
import CreateFolderForm from './CreateFolderForm.vue'
import UpdateFileForm from './UpdateFileForm.vue'
import download from '@/utils/download'
import { computed } from 'vue'
import { useUserStore } from '@/store/modules/user'

defineOptions({ name: 'FileSelect' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const userStore = useUserStore()

const props = defineProps<{
  modelValue: string[],
  folderDisabled: Boolean,
}>()
const emit = defineEmits<{
  (e: 'update:modelValue', value: string[]): void
}>()
const baseFileUrl = import.meta.env.VITE_BASE_FILE_URL // 文件的基础地址
const localCheckedFiles = ref<string[]>([])
const checkedFiles = computed({
  get: () => props.modelValue !== undefined ? props.modelValue : localCheckedFiles.value,
  set: (val: string[]) => {
    if (props.modelValue !== undefined) {
      emit('update:modelValue', val)
    } else {
      localCheckedFiles.value = val
    }
  }
})

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<FileApi.FilePresignedUrlRespVO[]>([]) // 列表的数据

const queryParams = reactive({
  pageNo: 1,
  pageSize: 24,
  name: undefined,
  type: undefined,
  path: undefined,
  title: undefined,
  parentId: 0,
  fileClass: undefined,
  isShare: undefined,
  isFolder: undefined,
  isUsed: undefined,
  searchType: 'my',
  createTime: []
})
const breadcuembDataList = ref([{ id: 0, parentId: 0, name: '文件管理' }]) // 面包屑的列表
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await FileApi.getFilePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改文件名操作 */
const formFileNameRef = ref()
const openFileNameForm = (id: number | any) => {
  formFileNameRef.value.open(id, queryParams.parentId, 1)
}

/** 修改文件或文件夹信息 */
const formUpdateRef = ref()
const openUpdateForm = (id: number | any, type: string) => {
  console.log(id, type)
  formUpdateRef.value.open(id, type)
}

const officeView = ref({
  url: '',
  dialog: false,
  type: '',
  title: '',
  xlsOptions: {
    xls: false,       //预览xlsx文件设为false；预览xls文件设为true
    minColLength: 0,  // excel最少渲染多少列，如果想实现xlsx文件内容有几列，就渲染几列，可以将此值设置为0.
    minRowLength: 0,  // excel最少渲染多少行，如果想实现根据xlsx实际函数渲染，可以将此值设置为0.
    widthOffset: 10,  //如果渲染出来的结果感觉单元格宽度不够，可以在默认渲染的列表宽度上再加 Npx宽
    heightOffset: 10, //在默认渲染的列表高度上再加 Npx高
    beforeTransformData: (workbookData) => { return workbookData }, //底层通过exceljs获取excel文件内容，通过该钩子函数，可以对获取的excel文件内容进行修改，比如某个单元格的数据显示不正确，可以在此自行修改每个单元格的value值。
    transformData: (workbookData) => { return workbookData }, //将获取到的excel数据进行处理之后且渲染到页面之前，可通过transformData对即将渲染的数据及样式进行修改，此时每个单元格的text值就是即将渲染到页面上的内容
  }
})

// 查看文件
const openViewForm = (item: FileApi.FilePresignedUrlRespVO) => {
  console.log(item)
  //查看图片
  if (item.fileClass == OaFileClassType.IMAGE) {
    createImageViewer({ urlList: [item.url] })
  } else if (item.fileClass == OaFileClassType.VIDEO) {
    //查看视频
    createVideoViewer({ url: item.url, poster: item.url })
  } else if (item.fileClass == OaFileClassType.OFFICE) {
    //https://501351981.github.io/vue-office/examples/docs/guide/
    //word
    if (item.path.indexOf('.doc') > -1) {
      officeView.value.url = item.url
      officeView.value.dialog = true
      officeView.value.type = 'doc'
    }
    else if (item.path.indexOf('.xlsx') > -1) {
      //WARNING 目前只支持xlsx文件预览，不支持xls文件。
      officeView.value.url = item.url
      officeView.value.dialog = true
      officeView.value.type = 'xlsx'
    }
    else if (item.path.indexOf('.pdf') > -1) {
      officeView.value.url = item.url
      officeView.value.dialog = true
      officeView.value.type = 'pdf'
    }
    else {
      message.error('暂不支持该文件类型预览,请下载后查看')
    }
  } else if (item.fileClass == OaFileClassType.ON_LINE) {
    //todo 在线文档
    formUpdateRef.value.open(item.id, 'online', true)
  } else if (item.fileClass == OaFileClassType.AUDIO) {
    officeView.value.title = item.name || '音频预览'
    officeView.value.url = item.url
    officeView.value.dialog = true
    officeView.value.type = 'audio'

    //todo 音频文件,可参照AI模块. /ai/music/index
  } else {
    message.error('暂不支持该文件类型预览,请下载后查看')
  }

}

/** 上传文件 */
const openUploadFormRef = ref()
const openUploadForm = () => {
  openUploadFormRef.value.open(queryParams.parentId)
}

/** 复制到剪贴板方法 */
const copyToClipboard = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    message.success('复制成功')
  })
}

/** 删除按钮操作 */
const handleDelete = async (item: any) => {
  try {
    const b = await FileApi.fileExist(item.id)
    if (b) {
      message.error('文件已被使用，不能删除')
      return
    }
    // 删除的二次确认
    if (item.isFolder == 1) {
      await message.delConfirm("文件夹下如果存在文件或文件夹，则无法删除")
    } else {
      await message.delConfirm()
    }
    // 发起删除
    await FileApi.deleteFile(item.id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 文件类型切换事件 */
const handleMenuClick = async (e: any) => {
  console.log(e)
  // if (e == 999) {
  //   queryParams.searchType = 'myShare'
  // } else {
  //   queryParams.fileClass = e
  // }

  if (e == 0) {
    queryParams.fileClass = undefined
    queryParams.searchType = 'my'
  }
  // else if(e==999){
  //   queryParams.searchType = 'myShare'
  //   queryParams.fileClass = undefined
  // }
  getList()
}
/** 点击我的分享按钮 */
const handleMyShareClick = async () => {
  queryParams.searchType = 'myShare'
  await getList()
}
/** 双击文件夹事件 */
const handleDoubleClick = async (item: any) => {
  if (item.isFolder == 1) {
    queryParams.parentId = item.id
    await getList()
    breadcuembDataList.value.push({ id: item.id, parentId: item.parentId, name: item.title })
  }
}



/**  面包屑点击事件 */
const handleBreadcrumbClick = async (item: any) => {
  queryParams.parentId = item.id
  await getList()
  breadcuembDataList.value = breadcuembDataList.value.slice(0, breadcuembDataList.value.indexOf(item) + 1)
}

/** 文件下载 */
const handleDownload = async (item) => {
  download.file(item.url, item.name || 'download.jpg')
  // try {
  //   // fetch方式（支持跨域，需要服务器配置CORS）
  //   const response = await fetch(item.url)
  //   if (!response.ok) throw new Error('文件获取失败')

  //   const blob = await response.blob()
  //   const url = URL.createObjectURL(blob)

  //   const link = document.createElement('a')
  //   link.href = url
  //   link.download = item.name || 'download.jpg'
  //   document.body.appendChild(link)
  //   link.click()

  //   // 清理
  //   setTimeout(() => {
  //     document.body.removeChild(link)
  //     URL.revokeObjectURL(url)
  //   }, 100)
  // } catch (error) {
  //   message.error('文件下载失败:')
  // }
}

/** 文件共享/取消共享操作 */
const handleShare = async (item: any, isShare: number) => {
  try {
    const confirmMsg = isShare ? '确定要共享该文件吗？' : '确定要取消共享该文件吗？';
    await message.confirm(confirmMsg)
    await FileApi.updateDetail({ id: item.id, isShare })
    message.success(isShare ? '共享成功' : '已取消共享')
    await getList()
  } catch (e) {
    message.error('操作失败')
  }
}

/** 批量删除 */
const handleBatchDelete = async () => {
  if (!checkedFiles.value.length) return message.error('请先选择文件');
  const b = await FileApi.fileExist(checkedFiles.value.join(','))
  if(b){
    message.error('文件已被使用，不能删除')
    return
  }
  await message.delConfirm('确定要批量删除选中的文件吗？')
  for (const id of checkedFiles.value) {
    await FileApi.deleteFile(id)
  }
  message.success('批量删除成功')
  await getList()
}
/** 批量编辑（这里只做演示，实际可弹窗批量编辑） */
const handleBatchEdit = async () => {
  if (checkedFiles.value.length === 0) return message.error('请先选择文件');
  if (checkedFiles.value.length > 1) return message.error('只能选择一个文件进行编辑');
  // 只允许单选时弹出编辑弹窗
  openUpdateForm(checkedFiles.value[0], '')
  await getList()
}
/** 批量共享/取消共享 */
const handleBatchShare = async (isShare: number) => {
  if (!checkedFiles.value.length) return message.error('请先选择文件');
  const confirmMsg = isShare ? '确定要批量共享选中的文件吗？' : '确定要批量取消共享选中的文件吗？';
  await message.confirm(confirmMsg)
  // 先检查是否包含文件夹
  for (const id of checkedFiles.value) {
    const file = list.value.find(item => item.id == Number(id))
    if (file && file.isFolder == 1) {
      message.error('文件夹下存在文件或文件夹，无法共享/取消共享')
      return
    }
  }
  for (const id of checkedFiles.value) {
    await FileApi.updateDetail({ id, isShare })
  }
  message.success(isShare ? '批量共享成功' : '批量取消共享成功')
  await getList()
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
:deep(.el-input-group__append) {
  background-color: var(--el-color-primary) !important;
  color: var(--el-color-white) !important;
  box-shadow: 0 1px 0 0 var(--el-color-primary) inset, 0 -1px 0 0 var(--el-color-primar) inset, -1px 0 0 0 var(--el-color-primary) inset
}

.affix-container {
  text-align: center;
  height: 400px;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
}

.checkbox-wrapper-16 *,
.checkbox-wrapper-16 *:after,
.checkbox-wrapper-16 *:before {
  box-sizing: border-box;
}

.checkbox-wrapper-16 .checkbox-input {
  clip: rect(0 0 0 0);
  -webkit-clip-path: inset(100%);
  clip-path: inset(100%);
  height: 1px;
  overflow: hidden;
  position: absolute;
  white-space: nowrap;
  width: 1px;
}


.checkbox-wrapper-16 .checkbox-input:checked+.checkbox-tile {
  border-color: #2260ff;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  color: #2260ff;
}

.checkbox-wrapper-16 .checkbox-input:checked+.checkbox-tile:before {
  transform: scale(1);
  opacity: 1;
  background-color: #2260ff;
  border-color: #2260ff;
}

.checkbox-wrapper-16 .checkbox-input:checked+.checkbox-tile .checkbox-icon,
.checkbox-wrapper-16 .checkbox-input:checked+.checkbox-tile .checkbox-label {
  color: #2260ff;
}

.checkbox-wrapper-16 .checkbox-input:focus+.checkbox-tile {
  border-color: #2260ff;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1), 0 0 0 4px #b5c9fc;
}

.checkbox-wrapper-16 .checkbox-input:focus+.checkbox-tile:before {
  transform: scale(1);
  opacity: 1;
}

.checkbox-wrapper-16 .checkbox-tile {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 0.5rem;
  border: 1px solid #b5bfd96c;
  background-color: #fff;
  transition: 0.15s ease;
  cursor: pointer;
  position: relative;
}

.checkbox-wrapper-16 .checkbox-tile:before {
  content: "";
  position: absolute;
  display: block;
  width: 1.25rem;
  height: 1.25rem;
  border: 1px solid #b5bfd96c;
  background-color: #fff;
  border-radius: 50%;
  top: 0.25rem;
  left: 0.25rem;
  opacity: 0;
  transform: scale(0);
  transition: 0.25s ease;
  background-size: 12px;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);

}

.checkbox-wrapper-16 .checkbox-tile:hover {
  border-color: #2260ff;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}

.checkbox-wrapper-16 .checkbox-dropdown {
  opacity: 0;
  transform: scale(0.8);
  transition: all 0.7s cubic-bezier(0.25, 0.8, 0.25, 1);
  pointer-events: none;
}

.checkbox-wrapper-16 .checkbox-tile:hover .checkbox-dropdown {
  opacity: 1;
  transform: scale(1);
  pointer-events: auto;
}

.checkbox-wrapper-16 .checkbox-tile:hover:before {
  transform: scale(1);
  opacity: 1;
}

.checkbox-wrapper-16 .checkbox-icon {
  transition: 0.375s ease;
  color: #494949;
}

.checkbox-wrapper-16 .checkbox-icon svg {
  width: 3rem;
  height: 3rem;
}

.checkbox-wrapper-16 .checkbox-label {
  color: #707070;
  transition: 0.375s ease;
  text-align: center;
}
</style>
